package grpcs

import (
	"context"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/auths"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/loggers"
	grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
	grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
	grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
	grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
	grpc_opentracing "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing"
	"github.com/grpc-ecosystem/go-grpc-middleware/util/metautils"
	grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
	"go.uber.org/zap"
	"google.golang.org/grpc"
)

type ServerOptionConfig struct {
	Logger        *zap.Logger
	RbacPublicKey string
}

func DefaultServerOptions(config ServerOptionConfig) []grpc.ServerOption {
	var opts []grpc.ServerOption
	// 设置通用拦截器
	opts = append(opts, grpc.ChainUnaryInterceptor(grpc_middleware.ChainUnaryServer(
		grpc_recovery.UnaryServerInterceptor(),
		grpc_ctxtags.UnaryServerInterceptor(),
		grpc_opentracing.UnaryServerInterceptor(),
		grpc_prometheus.UnaryServerInterceptor,
		grpc_zap.UnaryServerInterceptor(config.Logger),
		func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
			var newCtx context.Context
			var err error
			token := metautils.ExtractIncoming(ctx).Get("Authorization")
			loggers.Info("grpc token", ctx, zap.String("token", token))
			if token != "" {
				publicKey := config.RbacPublicKey
				newCtx, err = auths.NewCtxWithRbacAuth(publicKey, token, ctx)
				if err != nil {
					return nil, err
				}
			} else {
				newCtx = ctx
			}
			return handler(newCtx, req)
		},
	)))
	return opts
}
